<?php
namespace Admin\Controller;

/***
 * Class CommonController
 * @package Admin\Controller
 */
Class CommonController extends AdminController
{
    protected $model;   // 当前数据模型
    protected $tableName='';   // 当前数据模型对应表面

    public function _initialize()
    {
        parent::_initialize();
        $this->assign('user', session('user_auth'));        // 获取用户session数据
        if($this->tableName!==null)
            $this->tableName = $this->tableName ? $this->tableName : lcfirst(CONTROLLER_NAME);
        $this->model = @D($this->tableName);
    }

    /**
     * [index 默认列表页]
     * @return [type] [description]
     */
    public function index()
    {
        $map = $this->_search();
        if (!empty($this->model)) {
//            C('LIST_ROWS', 10);    // 修改当前页数量
            $list = $this->lists($this->model, $map);
            $this->assign($this->tableName.'List', $list);
        }
        $this->display();
    }

    /**
     * [_search 搜索/获取查询条件]
     * @return [type] [description]
     */
    protected function _search()
    {
        $map = array();
        foreach ($this->model->getDbFields() as $key => $val) {
            if (isset($_REQUEST['key']) && $_REQUEST['key'] != '') {
                if (in_array($val, C('SEARCH_KEY_LIST'))) {
                    $map [$val] = array('like', '%' . trim($_REQUEST['key']) . '%');
                }
            }
        }
        if (IS_POST && isset($_REQUEST['key']) && $_REQUEST['key'] != '' && !empty($map)) {
            $map['_logic'] = 'or';
            $where['_complex'] = $map;
            return $where;
        } else {
            return $map;
        }
    }

    /**
     * [add 添加]
     */
    public function add()
    {
        if (IS_POST) {
            $data = $this->model->create();
            foreach($data as $key=>$value){
                if(is_numeric(strpos($key, 'time'))){
                    $data[$key] = strtotime($value);
                }
            }
            empty($data['create_time']) && $data['create_time'] = time();  // 创建时间
            empty($data['status']) && $data['status'] = 1;  // 创建时间
            if (empty($data)) {
                $this->mtReturn(300, '失败，请检查值是否已经存在', $_REQUEST['navTabId'], true);
            }
            if ($id=$this->model->add($data)) {
                $this->mtReturn(200, "新增成功" . $id, $_REQUEST['navTabId'], true);
            }else{
                $this->mtReturn(300, '添加数据失败', $_REQUEST['navTabId'], true);
            }
        }
        $this->display();
    }

    /**
     * [edit 编辑/修改]     限制更新单条数据
     * @return [type] [description]
     */
    public function edit()
    {
        if (IS_POST) {
            $data = I('request.');
            if (false === $data = $this->model->create($data)) {
                $errorMessahe = $this->model->getError() ? $this->model->getError() : '失败，请检查值是否已经存在';
                $this->mtReturn(300, $errorMessahe, $_REQUEST['navTabId'], true);
            }
            foreach($data as $key=>$value){
                if(is_numeric(strpos($key, 'time'))){
                    $data[$key] = strtotime($value);
                }
            }
            if (is_numeric($this->model->save($data))) {
                $this->mtReturn(200, "编辑成功!", $_REQUEST['navTabId'], true);
            }
            $this->mtReturn(300, "编辑失败!", $_REQUEST['navTabId'], true);
        }
        if($id = I('get.id')){  // 获取当前数据
            $arr = $this->model->find($id);
            $this->assign('vo', $arr);
        }
        $this->display();
    }

    /**
     * [toggleStatus 启用/禁用]
     * @return [type] [description]
     */
    public function toggleStatus()
    {
        $id = I('request.id');
        if ($id) {
            $data = $this->model->find($id);
            $data['id'] = $id;
            if ($data['status'] == 1) {
                $data['status'] = 0;
                $msg = '禁用';
            } else {
                $data['status'] = 1;
                $msg = '启用';
            }
            $res = $this->model->save($data);
            if($res == false)
            {
                $this->mtReturn(200, $msg.'失败!', $_REQUEST['navTabId'], false);
            }
            $this->mtReturn(200, $msg.'成功!', $_REQUEST['navTabId'], false);
        }
        $this->mtReturn(300, '操作失败!', $_REQUEST['navTabId'], false);
    }

    /**
     * [del 删除]
     * @return [type] [description]
     */
    public function del()
    {
        $id = I('request.id');
        if ($id) {
            $this->model->delete($id);
            $this->mtReturn(200, '删除成功!', $_REQUEST['navTabId'], false);
        }
        $this->mtReturn(300, '删除失败!', $_REQUEST['navTabId'], false);
    }


    /**
     * 上传单个文件
     * @param string $image
     * @param bool|false $isImg true时是$_FILES数据, false时是图片文件元素名称
     * @return string
     */
    protected function _upload($image='img', $isImg=false) {
        header("Content-Type:text/html;charset=utf-8");
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg','gif','png','jpeg');// 设置附件上传类
        $upload->savePath  =      'Images/'; // 设置附件上传目录
        // 上传文件
        if(!$isImg){
            $image = $_FILES[$image];
        }
        $info   =   $upload->uploadOne($image);

        if(!$info) {// 上传错误提示错误信息
            throw new \Exception($upload->getError());
        }
        return  $upload->rootPath.$info['savepath'].$info['savename'];

    }


    /**
     * 上传单个文件
     */
    function upload(){
        try{
            $imagePath = $this->_upload('file');
        }catch (\Exception $e){
            $this->error($e->getCode().'_'.$e->getMessage());
        }

        $id_name = I('request.field_id', 'id');     // 操作的数据id字段名
        $id = I('request.id');                      // 操作的数据id
        $field = I('request.field_name', 'url');    // 操作的数据id

        $where = array();
        $where[$id_name] = $id;     // 操作的数据id
        $data = array();
        $data[$field] = $imagePath;     // 操作的数据id
        $result = $this->model->where($where)->save($data);
        if(is_numeric($result)){
            $data = array();
            $data['statusCode'] = "200";
            $data['message'] = '上传图片成功!';
            $data['filename'] = urlAddDomain($imagePath);
            $this->ajaxReturn($data);
        }
        $this->error('上传图片失败!');
    }

    /**
     * 获取微信错误信息
     * @param $code
     * @return mixed
     */
    protected function getWechatError($code)
    {
        $errcode = array(
            "-1" => "系统繁忙",
            "40001" => "获取access_token时AppSecret错误，或者access_token无效",
            "40002" => "不合法的凭证类型",
            "40003" => "不合法的OpenID",
            "40004" => "不合法的媒体文件类型",
            "40005" => "不合法的文件类型",
            "40006" => "不合法的文件大小",
            "40007" => "不合法的媒体文件id",
            "40008" => "不合法的消息类型",
            "40009" => "不合法的图片文件大小",
            "40010" => "不合法的语音文件大小",
            "40011" => "不合法的视频文件大小",
            "40012" => "不合法的缩略图文件大小",
            "40013" => "不合法的APPID",
            "40014" => "不合法的access_token",
            "40015" => "不合法的菜单类型",
            "40016" => "不合法的按钮个数",
            "40017" => "不合法的按钮个数",
            "40018" => "不合法的按钮名字长度",
            "40019" => "不合法的按钮KEY长度",
            "40020" => "不合法的按钮URL长度",
            "40021" => "不合法的菜单版本号",
            "40022" => "不合法的子菜单级数",
            "40023" => "不合法的子菜单按钮个数",
            "40024" => "不合法的子菜单按钮类型",
            "40025" => "不合法的子菜单按钮名字长度",
            "40026" => "不合法的子菜单按钮KEY长度",
            "40027" => "不合法的子菜单按钮URL长度",
            "40028" => "不合法的自定义菜单使用用户",
            "40029" => "不合法的oauth_code",
            "40030" => "不合法的refresh_token",
            "40031" => "不合法的openid列表",
            "40032" => "不合法的openid列表长度",
            "40033" => "不合法的请求字符，不能包含\uxxxx格式的字符",
            "40035" => "不合法的参数",
            "40038" => "不合法的请求格式",
            "40039" => "不合法的URL长度",
            "40050" => "不合法的分组id",
            "40051" => "分组名字不合法",
            "41001" => "缺少access_token参数",
            "41002" => "缺少appid参数",
            "41003" => "缺少refresh_token参数",
            "41004" => "缺少secret参数",
            "41005" => "缺少多媒体文件数据",
            "41006" => "缺少media_id参数",
            "41007" => "缺少子菜单数据",
            "41008" => "缺少oauth code",
            "41009" => "缺少openid",
            "42001" => "access_token超时",
            "42002" => "refresh_token超时",
            "42003" => "oauth_code超时",
            "43001" => "需要GET请求",
            "43002" => "需要POST请求",
            "43003" => "需要HTTPS请求",
            "43004" => "需要接收者关注",
            "43005" => "需要好友关系",
            "44001" => "多媒体文件为空",
            "44002" => "POST的数据包为空",
            "44003" => "图文消息内容为空",
            "44004" => "文本消息内容为空",
            "45001" => "多媒体文件大小超过限制",
            "45002" => "消息内容超过限制",
            "45003" => "标题字段超过限制",
            "45004" => "描述字段超过限制",
            "45005" => "链接字段超过限制",
            "45006" => "图片链接字段超过限制",
            "45007" => "语音播放时间超过限制",
            "45008" => "图文消息超过限制",
            "45009" => "接口调用超过限制",
            "45010" => "创建菜单个数超过限制",
            "45015" => "回复时间超过限制",
            "45016" => "系统分组，不允许修改",
            "45017" => "分组名字过长",
            "45018" => "分组数量超过上限",
            "46001" => "不存在媒体数据",
            "46002" => "不存在的菜单版本",
            "46003" => "不存在的菜单数据",
            "46004" => "不存在的用户",
            "47001" => "解析JSON/XML内容错误",
            "48001" => "api功能未授权",
            "50001" => "用户未授权该api",
        );
        return $errcode[$code];
    }

}